package org.lucky.admin.controller;

import cn.shuibo.annotation.Decrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Parameter;
import org.lucky.admin.mapper.LoginInfoMapper;
import org.lucky.admin.query.AdminQuery;
import org.lucky.admin.query.UserQuery;
import org.lucky.admin.service.IAdminService;
import org.lucky.admin.service.IMenuService;
import org.lucky.admin.util.ExcelUtil;
import org.lucky.admin.util.RedisUtil;
import org.lucky_common.domain.Admin;
import org.lucky_common.domain.InviteParam;
import org.lucky_common.domain.LoginInfo;
import org.lucky_common.domain.Menu;
import org.lucky_common.dto.LoginDto;
import org.lucky_common.util.AjaxResult;
import org.lucky_common.util.MD5Utils;
import org.lucky_common.util.PageList;
import org.lucky_common.vo.AdminExportVo;
import org.lucky_common.vo.InviteExportVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private IAdminService adminService;

    @Resource
    private IMenuService menuService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private LoginInfoMapper loginInfoMapper;

    @PutMapping("/login")
    @Decrypt
    public AjaxResult login(@RequestBody LoginDto loginDto, HttpServletRequest request){
        return adminService.login(loginDto,request);
    }

    @GetMapping("/getAdmin/{adminId}")
    public AjaxResult getEmployeeMenu(@PathVariable("adminId")Long employeeId){
        List<Menu> menus = menuService.getEmployeeMenu(employeeId);
        return AjaxResult.success(menus);
    }

    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        try {
            System.out.println(request.getHeader("TOKEN"));
            String token = request.getHeader("TOKEN");
            boolean exists = redisUtil.exists(token);
            if (!exists) {
                return AjaxResult.error("请重新登录！");
            }
            if (token == null ){
                return AjaxResult.error("请重新登录！");
            }
            //redis
            redisUtil.logout(token);
            return AjaxResult.successMsg("登出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("登出失败");
        }
    }

    @PutMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody Admin employee) {
        if ("".equals(employee.getHeadImage())){
            employee.setHeadImage("/images/head/avatar.png");
        }
        if (employee.getId() == null) {
            adminService.saveAdmin(employee);
        } else {
            adminService.updateById(employee);
            LoginInfo loginInfo = loginInfoMapper.selectOne(new QueryWrapper<LoginInfo>().eq("username", employee.getUsername()));
            loginInfo.setUsername(employee.getUsername());
            loginInfo.setHeadImg(employee.getHeadImage());
            loginInfo.setEmail(employee.getEmail());
            loginInfoMapper.updateById(loginInfo);
        }
        return AjaxResult.success();
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        try {
            adminService.removeById(id);
            loginInfoMapper.deleteById(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("Error");
        }
    }

    @DeleteMapping("/deleteList")
    public AjaxResult deleteList(@RequestBody ArrayList<Long> ids) {
        try {
            adminService.removeByIds(ids);
            loginInfoMapper.deleteBatchIds(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    @PostMapping
    public AjaxResult queryPage(@RequestBody AdminQuery employeeQuery) {
        Page<Admin> page = new Page<Admin>(employeeQuery.getPage(),employeeQuery.getRows(),true);
        page = adminService.page(page,new QueryWrapper<Admin>().like("username",employeeQuery.getKeyword()).or().like("email",employeeQuery.getKeyword()));
        page.getRecords().forEach(e->{
            e.setSalt("");
        });
        PageList<Admin> pageList = new PageList<Admin>(page.getTotal(),page.getRecords());
        return AjaxResult.success(pageList);
    }

    @GetMapping("/{id}")
    public AjaxResult queryById(@PathVariable("id") Long id) {
        return AjaxResult.success(adminService.getById(id));
    }


    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response) {
        //查询要导出的数据
        List<AdminExportVo> users = adminService.getUserExportList();
        AdminExportVo.threadLocal_collectionSize.set( users.size() );
        AdminExportVo.threadLocal_insertIndex.set( 1 );
        ExcelUtil.exportExcelX(users, "管理员信息表", "sheet1", AdminExportVo.class, "管理员信息表.xlsx", response);
    }

    @PutMapping("/exportMore")
    public void exportMore11(@RequestBody ArrayList<AdminExportVo> data, HttpServletResponse response) {
        List<AdminExportVo> userExportVo = new ArrayList<>(data);
        AdminExportVo.threadLocal_collectionSize.set( userExportVo.size() );
        AdminExportVo.threadLocal_insertIndex.set( 1 );
        ExcelUtil.exportExcelX(userExportVo, "管理员信息表", "sheet1", AdminExportVo.class, "管理员信息表.xlsx", response);
    }

}
